package com.definity.toolkit.web.taglib;

import javax.servlet.jsp.JspException;

import org.apache.commons.beanutils.MethodUtils;

public class SelectEnumTag extends ComponentFormTag {

	private static final long serialVersionUID = -188892331724315289L;

	private String enumerated;

	public SelectEnumTag() {

	}

	public void setEnumerated(String domain) {
		this.enumerated = domain;
	}

	@Override
	protected String getComponentName() {
		return "select-enum";
	}
	
	@Override
	protected int doStartTag(FormTag formTag, StringBuilder html) throws JspException {
		super.doStartTag(formTag, html);

		return EVAL_BODY_INCLUDE;
	}

	@Override
	protected String createStartTag(String name, String id, Object value) throws JspException {
		StringBuilder buffer = new StringBuilder();
		buffer.append("<select name='");
		buffer.append(id);
		buffer.append("' id='");
		buffer.append(id);
		buffer.append("'");
		buffer.append(createStyleClass("common_field"));
		buffer.append(">");

		return buffer.toString();
	}

	@Override
	protected String createEndTag(String name, String id, Object value) throws JspException {
		Class<?> enumType;

		try {
			enumType = Class.forName(enumerated);
		} catch (Exception e) {
			throw new JspException(e);
		}

		StringBuilder buffer = new StringBuilder();

		optionsByEnum(buffer, enumType, value);

		buffer.append("</select>");

		return buffer.toString();
	}

	protected void optionsByEnum(StringBuilder buffer, Class<?> enumType, Object defaulValue) {
		String name = enumType.getSimpleName() + ".";

		for (Object object : getValues(enumType)) {
			Object optionValue = object;
			String optionLabel = i18n().tl(name + object.toString());

			buffer.append("<option value='");
			buffer.append(optionValue);
			buffer.append("'");

			if (defaulValue != null && defaulValue.equals(optionValue)) {
				buffer.append(" selected='selected'");
			}

			buffer.append(">");
			buffer.append(optionLabel);
			buffer.append("</option>");
		}
	}

	protected Object[] getValues(Class<?> enumType) {
		try {
			return (Object[]) MethodUtils.invokeStaticMethod(enumType, "values", null);
		} catch (Exception e) {
			return null;
		}
	}

}
